﻿using System.Net;
using System;

namespace OpenWaves.Web
{
    public class HttpErrorHandlerInfo
    {
        public static HttpErrorHandlerInfo FromQueryString(string queryString, HttpStatusCode defaultStatusCode)
        {
            return new HttpErrorHandlerInfo(GetOriginalUrl(queryString), GetHttpStatusCodeOrDefault(queryString, defaultStatusCode));
        }

        private static string GetOriginalUrl(string queryString)
        {
            var errorInfo = Url.Decode(queryString);            
            if (String.IsNullOrEmpty(errorInfo))
                return String.Empty;

            var errorInfoSegments = errorInfo.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            return errorInfoSegments.Length < 2 ? String.Empty : errorInfoSegments[1];                 
        }

        private static HttpStatusCode GetHttpStatusCodeOrDefault(string queryString, HttpStatusCode defaultStatusCode)
        {
            var errorInfo = Url.Decode(queryString);
            if (String.IsNullOrEmpty(errorInfo))
                return defaultStatusCode;

            var errorInfoSegments = errorInfo.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (errorInfoSegments.Length == 0)
                return defaultStatusCode;

            int httpCode;
            if (Int32.TryParse(errorInfoSegments[0], out httpCode))
                return (HttpStatusCode)httpCode;

            return defaultStatusCode;
        }

        public string OriginalUrl { get; private set; }

        public HttpStatusCode StatusCode { get; private set; }

        private HttpErrorHandlerInfo(string originalUrl, HttpStatusCode statusCode)
        {
            this.OriginalUrl = originalUrl;
            this.StatusCode = statusCode;
        }
    }
}